// ajax(url),
// ajax(url,option),
// ajax(option)
// var option = {
//     methods: 'get',//方法默认get
//     contentType:"application/x-www-form-urlencoded; charset=UTF-8",
//     data:{},
//     headers :{},
//     success:function(data, status, xhr){},
//     error:function(data,xhr,textStatus),
//     timeout:5000,
//     url:''
// }

const baseUrl = "http://wangsr.vip:3012/api/v1"

function ajax() {
    let option, url;
    if (typeof arguments[0] == 'object') {
        option = arguments[0]
        url = option.url
        if (!url) { throw Error('没有Url参数') }
    } else if (typeof arguments[0] == 'string') {
        url = arguments[0]
        option = arguments[1]
        if (!option) { option = {} }
    } else {
        throw Error('参数不合法')
    }
    if (!url) throw Error('url参数不存在')
    let method = (option.method || 'get').trim().toUpperCase()
    let contentType = option.contentType || "application/x-www-form-urlencoded; charset=UTF-8"
    let data = option.data || {}
    let dataStr = null;
    let paramsStr = ''
    for (let key in data) {
        paramsStr += `${key}=${data[key]}&`
    }
    paramsStr = paramsStr.slice(0, -1)
    if (method == 'GET') {
        if (paramsStr) {
            url += '?' + paramsStr
        }
    } else {
        dataStr = paramsStr
    }
    // get -> {a:1,b:2} -> a=1&b=2 -> a.com/h?a=1&b=2  xhr.send( )
    // post -> {a:1,b:2} -> a=1&b=2 -> a.com/h         xhr.send(a=1&b=2)  "application/x-www-form-urlencoded"
    // post -> {a:1,b:2} -> '{"a":1,"b":2}' -> a.com/h xhr.send('{"a":1,"b":2}')  "application/json"
    const xhr = new XMLHttpRequest()

    xhr.open(method, url)
    //设置请求
    xhr.setRequestHeader("Content-Type", contentType)
    xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest')
    if (option.headers) {
        for (let key in option.headers) {
            xhr.setRequestHeader(key, option.headers[key])
        }
    }
    //请求前执行函数
    if (ajaxSend && typeof ajaxSend === 'function') {
        ajaxSend(xhr, option)
    }

    xhr.send(dataStr)
    //#4.监听xhr的readystate的变化，使用onreadystatechange函数
    xhr.onload = function (e) {
        if (xhr.status >= 200 && xhr.status < 300) {
            if (typeof option.success == 'function') {
                let res = null;
                try {
                    res = JSON.parse(xhr.responseText)
                } catch (e) {
                    console.log(e)
                }
                option.success(res, xhr.statusText, xhr)
            }
        } else {
            if (typeof option.error == 'function') {
                const res = JSON.parse(xhr.responseText)
                option.error(res, xhr.statusText, xhr)
            }
        }
        // 请求结束，以后可封装到全局请求结束设置函数
        if (ajaxComplete && typeof ajaxComplete === 'function') {
            ajaxComplete(xhr, option)
        }


    }
}

//在open之前执行的函数
function ajaxSend(xhr, option) {
    const token = sessionStorage.getItem('token') || localStorage.getItem('token')
    if (token) {
        xhr.setRequestHeader("authorization", token)
    }

};
//请求结束后执行
function ajaxComplete(xhr, option) {
    if (xhr.status == 401) {
        localStorage.setItem('token', null)
    }
}
